﻿using FlyingEye.HttpServices.Requests;
using FlyingEye.HttpServices.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.HttpServices
{

    /// <summary>
    /// 设备客户端服务
    /// </summary>
    public class DeviceHubService : ITransientDependency
    {
        private readonly ILogger<DeviceHubService> _logger;

        private readonly HttpClientService _httpClientService;

        private readonly IOptions<DeviceClientServiceOptions> _options;

        private DeviceClientServiceOptions Options => _options.Value;

        public DeviceHubService(ILogger<DeviceHubService> logger, HttpClientService httpClientService, IOptions<DeviceClientServiceOptions> options)
        {
            _logger = logger;
            _httpClientService = httpClientService;
            _options = options;
        }

        /// <summary>
        /// 读取一个数字数据
        /// </summary>
        public async Task<ReadValueResponse> ReadNumericValeuAsync(string resourceId, ReadNumericValueRequest request)
        {
            try
            {
                var result = await _httpClientService.PostAsync<ReadValueResponse,
                    ReadNumericValueRequest>(Options.BaseUri + $"/api/device-app-service/v1.0/device-clients/{resourceId}/read-numeric-value", request);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "读取 PLC 数据 HTTP 请求异常");
                return new ReadValueResponse(false, ex.Message, null);
            }
        }

        /// <summary>
        /// 读取一个字符串数据
        /// </summary>
        public async Task<ReadValueResponse> ReadStringValueAsync(string resourceId, ReadStringValueRequest request)
        {
            try
            {
                var result = await _httpClientService.PostAsync<ReadValueResponse,
                    ReadStringValueRequest>(Options.BaseUri + $"/api/device-app-service/v1.0/device-clients/{resourceId}/read-string-value", request);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "读取 PLC 数据 HTTP 请求异常");
                return new ReadValueResponse(false, ex.Message, null);
            }
        }
    }
}
